package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("StandardlevelService")
@Transactional

public class StandardlevelServiceImpl extends CmiEmaService implements StandardlevelService {
	public StandardlevelServiceImpl() {
	}

	@Transactional
	public Standardlevel saveStandardlevel(Standardlevel standardlevel) {
		Set<Standard> existingStandardsForStandardlevel = new HashSet<Standard>();

		Set<Standard> selectedStandardsForStandardlevel = standardlevel.getStandardsForStandardlevel();

		if (standardlevel.getId() == null) {

			Standardlevel existingStandardlevel = standardlevelDAO
					.findStandardlevelByPhysicalPrimaryKey(standardlevel.getName());

			if (isEquals(standardlevel, existingStandardlevel)) {
				return existingStandardlevel;
			}

			standardlevel = standardlevelDAO.store(standardlevel);
			standardlevelDAO.flush();

			for (Standard relatedStandard : selectedStandardsForStandardlevel) {
				relatedStandard.setStandardlevel(standardlevel);
				standardDAO.store(relatedStandard);
			}
		} else {
			Standardlevel existingStandardlevel = standardlevelDAO.findStandardlevelByPrimaryKey(standardlevel.getId());

			existingStandardsForStandardlevel = existingStandardlevel.getStandardsForStandardlevel();

			Set<Standard> prepareDeleteStandardsForStandardlevel = new HashSet<Standard>();
			Set<Standard> prepareAddStandardsForStandardlevel = new HashSet<Standard>();

			prepareDeleteStandardsForStandardlevel.addAll(selectedStandardsForStandardlevel);
			prepareDeleteStandardsForStandardlevel.addAll(existingStandardsForStandardlevel);

			prepareAddStandardsForStandardlevel.addAll(selectedStandardsForStandardlevel);
			prepareAddStandardsForStandardlevel.addAll(existingStandardsForStandardlevel);

			prepareDeleteStandardsForStandardlevel.removeAll(selectedStandardsForStandardlevel);
			prepareAddStandardsForStandardlevel.removeAll(existingStandardsForStandardlevel);

			for (Standard relatedStandard : prepareAddStandardsForStandardlevel) {
				relatedStandard.setStandardlevel(standardlevel);
				standardDAO.store(relatedStandard);
			}

			for (Standard relatedStandard : prepareDeleteStandardsForStandardlevel) {
				relatedStandard.setStandardlevel(null);
				standardDAO.store(relatedStandard);
			}
			standardlevel = standardlevelDAO.store(standardlevel);
			standardlevelDAO.flush();
		}

		standardDAO.flush();
		return standardlevel;
	}

	public void deleteStandardlevel(Standardlevel standardlevel) {
		standardlevelDAO.remove(standardlevel);
		standardlevelDAO.flush();
	}

	@Transactional
	public void deleteStandardlevels(Set<Integer> deleteStandardlevelsId) {
		Query query = standardlevelDAO.createNamedQuery("deleteStandardlevelsById", -1, -1);
		query.setParameter(1, deleteStandardlevelsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Standardlevel> loadStandardlevels() {
		return standardlevelDAO.findAllStandardlevels();

	}

	@Transactional
	public Set<Standardlevel> loadReferenceStandardlevels(Set<Standardlevel> standardlevels) {
		Iterator<Standardlevel> standardlevelsIterator = standardlevels.iterator();
		Set<Standardlevel> referencedStandardlevels = new HashSet<>();
		while (standardlevelsIterator.hasNext()) {
			Standardlevel currentStandardlevel = standardlevelsIterator.next();

			if (!currentStandardlevel.getStandardsForStandardlevel().isEmpty()) {
				referencedStandardlevels.add(currentStandardlevel);
				continue;
			}
		}
		return referencedStandardlevels;
	}

	public Set<Standardlevel> loadStandardlevelsByIdSet(Set<Integer> standardlevelIdSet) {

		Iterator<Integer> standardlevelIdIterator = standardlevelIdSet.iterator();
		Set<Standardlevel> standardlevelSet = new HashSet<>();
		while (standardlevelIdIterator.hasNext()) {
			Integer id = standardlevelIdIterator.next();
			Standardlevel currentStandardlevel = standardlevelDAO.findStandardlevelById(id);
			standardlevelSet.add(currentStandardlevel);
		}
		return standardlevelSet;
	}

	@Transactional
	public List<Standardlevel> findAllStandardlevels(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Standardlevel>(standardlevelDAO.findAllStandardlevels(startResult, maxRows));
	}

	@Transactional
	public Standardlevel findStandardlevelByPrimaryKey(Integer id) {
		return standardlevelDAO.findStandardlevelByPrimaryKey(id);
	}

	@Transactional
	public Integer countStandardlevels() {
		return ((Long) standardlevelDAO.createQuerySingleResult("select count(o) from Standardlevel o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countStandardlevels(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Standardlevel.class);
		return ((Long) standardlevelDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countStandardlevelsByName(String queryName) {
		Query query = standardlevelDAO.createNamedQuery("countStandardlevelsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countStandardlevelsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Standardlevel.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadStandardlevelObjectReferencedSet(Standardlevel standardlevel) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> standardsIds = new HashSet<Integer>();
		for (Standard obj : standardlevel.getStandardsForStandardlevel()) {

			standardsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("standardsIds", standardsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadStandardlevelClassReferencedSet(Standardlevel standardlevel) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("standards", standardDAO.findAllStandards());

		return classReferencedSetMap;
	}

	public boolean isEquals(Standardlevel standardlevel, Object obj) {
		if (obj == standardlevel)
			return true;
		if (!(obj instanceof Standardlevel))
			return false;
		Standardlevel comparedStandardlevel = (Standardlevel) obj;
		if (!CheckPropertyEqual(standardlevel.getName(), comparedStandardlevel.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

